package com.wmwj.hxlj.mapper;

import com.wmwj.hxlj.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    // 查询用户数量
    @Select("SELECT COUNT(*) FROM user WHERE del_flag = 0 AND type = 0")
    int countUser();

    // 根据ID查询用户
    @Select("SELECT * FROM user WHERE id = #{id} AND del_flag = 0")
    User findById(Long id);

    // 根据用户名查询用户，支持模糊查询
    @Select("SELECT * FROM user WHERE account LIKE CONCAT('%', #{account}, '%') AND del_flag = 0")
    List<User> findByAccountLike(String account);

    //通过账号查询用户
    @Select("SELECT * FROM user WHERE account = #{account} AND del_flag = 0")
    User findByAccount(String account);

    //查看邮箱是否重复
    @Select("SELECT * FROM user WHERE email = #{email} AND del_flag = 0")
    User findByEmailLike(String email);

    // 根据邮箱查询用户
    @Select("SELECT * FROM user WHERE email = #{email} AND del_flag = 0")
    User findByEmail(String email);

    // 插入新用户
    @Insert("INSERT INTO user(account, nick_name, password, type, status, email, phone_number, " +
            "sex, avatar, unique_id, create_time, update_by, update_time, del_flag) " +
            "VALUES(#{account}, #{nickName}, #{password}, #{type}, #{status}, #{email}, " +
            "#{phoneNumber}, #{sex}, #{avatar}, #{uniqueId}, #{createTime}, #{updateBy}, " +
            "#{updateTime}, #{delFlag})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);

    // 更新用户信息
    @Update("<script>" +
            "UPDATE user " +
            "<set>" +
            "   <if test='nickName != null'>nick_name = #{nickName},</if>" +
            "   <if test='email != null'>email = #{email},</if>" +
            "   <if test='phoneNumber != null'>phone_number = #{phoneNumber},</if>" +
            "   <if test='avatar != null'>avatar = #{avatar},</if>" +
            "   <if test='sex != null'>sex = #{sex},</if>" +
            "</set>" +
            "WHERE id = #{id} AND del_flag = 0" +
            "</script>")
    int updateUser(User user);


    // 删除用户（软删除）
    @Update("UPDATE user SET del_flag = 1, update_by = #{updateBy}, update_time = NOW() " +
            "WHERE id = #{id} AND del_flag = 0")
    int deleteById(@Param("id") Long id, @Param("updateBy") String updateBy);

    // 删除用户（软删除）
    @Update("UPDATE user SET del_flag = 1, update_time = NOW() " +
            "WHERE id = #{id} AND del_flag = 0")
    int adminDeleteById(@Param("id") Long id);

    // 查询用户列表（支持多条件查询）
    @Select("<script>" +
            "SELECT * FROM user WHERE del_flag = 0" +
            "<if test='account != null and account != \"\"'> AND account LIKE CONCAT('%', #{account}, '%')</if>" +
            "<if test='nickName != null and nickName != \"\"'> AND nick_name LIKE CONCAT('%', #{nickName}, '%')</if>" +
            "<if test='type != null and type != \"\"'> AND type = #{type}</if>" +
            "<if test='status != null and status != \"\"'> AND status = #{status}</if>" +
            "<if test='email != null and email != \"\"'> AND email LIKE CONCAT('%', #{email}, '%')</if>" +
            "<if test='phoneNumber != null and phoneNumber != \"\"'> AND phone_number LIKE CONCAT('%', #{phoneNumber}, '%')</if>" +
            "<if test='sex != null and sex != \"\"'> AND sex = #{sex}</if>" +
            " ORDER BY create_time DESC" +
            "</script>")
    List<User> findList(User user);

    // 更新用户状态
    @Update("UPDATE user SET status = #{status}, update_by = #{updateBy}, update_time = NOW() " +
            "WHERE id = #{id} AND del_flag = 0")
    int updateStatus(@Param("id") Long id, @Param("status") String status, @Param("updateBy") String updateBy);

    // 修改密码
    @Update("UPDATE user SET password = #{newPassword}, update_by = #{updateBy}, update_time = NOW() " +
            "WHERE id = #{id} AND password = #{oldPassword} AND del_flag = 0")
    int updatePassword(@Param("id") Long id,
                      @Param("oldPassword") String oldPassword,
                      @Param("newPassword") String newPassword,
                      @Param("updateBy") String updateBy);

    // 重置密码,管理员
    @Update("UPDATE user SET password = #{password}, update_by = #{updateBy}, update_time = NOW() " +
            "WHERE id = #{id} AND del_flag = 0")
    int resetPassword(@Param("id") Long id,
                     @Param("password") String password,
                     @Param("updateBy") String updateBy);

    /**
     * 增加用户粉丝数量
     * @param id
     * @return
     */
    @Update("UPDATE user SET fans_count = fans_count + 1 WHERE id = #{id}")
    int incrementFollowCount(Long id);

    /**
     * 减少用户粉丝数量
     * @param id
     * @return
     */
    @Update("UPDATE user SET fans_count = fans_count - 1 WHERE id = #{id}")
    int decrementFollowCount(Long id);

    /**
     * 增加用户关注数量
     * @param followeeId
     * @return
     */
    @Update("UPDATE user SET follow_count = follow_count + 1 WHERE id = #{id}")
    int incrementFollowerCount(Long followeeId);

    /**
     * 减少用户关注数量
     * @param id
     * @return
     */
    @Update("UPDATE user SET follow_count = follow_count - 1 WHERE id = #{id}")
    int decrementFollowerCount(Long id);

    /**
     * 获取用户列表
     * @param pageStarts
     * @param pageSize
     * @return
     */
    @Select("SELECT * FROM user WHERE del_flag = 0 AND type = 0 ORDER BY create_time DESC LIMIT #{pageStarts}, #{pageSize}")
    List<User> getUserList(int pageStarts, int pageSize);

    /**
     * 管理员搜索用户
     * @param account
     * @param pageStarts
     * @param pageSize
     * @return
     */
    @Select("SELECT * FROM user WHERE del_flag = 0 AND type = 0 " +
            "AND (account LIKE CONCAT('%', #{account}, '%') OR nick_name LIKE CONCAT('%', #{account}, '%')) " +
            "ORDER BY create_time DESC LIMIT #{pageStarts}, #{pageSize}")
    List<User> adminSearchUsersByAccount(String account, int pageStarts, int pageSize);


    /**
     * 管理员搜索用户总数
     * @param account
     * @return
     */
    @Select("SELECT COUNT(*) FROM user WHERE del_flag = 0 AND account LIKE CONCAT('%', #{account}, '%') " +
            "OR nick_name LIKE CONCAT('%', #{account}, '%')")
    int adminCountByKeyword(String account);
}